package com.ruoyi.web.core.utils;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <pre>
 *
 * </pre>
 *
 * @author zhangli
 * @since 2023/9/24
 */
@Slf4j
public class SignUtils {

    /**
     * 拼接字符串
     *
     * @param object 对象
     * @param exclude 排除字段
     * @param suffix 后缀
     * @param withSeparator 是否添加分隔符（⼀定拼接属性名）
     * @param withFieldName 是否拼接属性名
     * @return String
     */
    public static String combineStr(Object object, Set<String> exclude, String suffix,
                                    boolean withSeparator, boolean withFieldName) {
        Class<?> clazz = object.getClass();
        List<Field> baseFields =
                Arrays.stream(clazz.getDeclaredFields()).collect(Collectors.toList());
        Class<?> superClazz = clazz.getSuperclass();
        while (superClazz != Object.class) {
            Field[] superFields = superClazz.getDeclaredFields();
            baseFields.addAll(Arrays.stream(superFields).collect(Collectors.toList()));
            superClazz = superClazz.getSuperclass();
        }
        List<Field> collect =
                baseFields.stream().sorted(Comparator.comparing(Field::getName)).collect(Collectors.toList());
        StringBuilder builder = new StringBuilder();
        for (Field field : collect) {
            try {
                field.setAccessible(true);
                if (!CollectionUtils.isEmpty(exclude) &&
                        exclude.contains(field.getName())) {
                    continue;
                }
                Optional.ofNullable(field.get(object)).ifPresent(v -> {
                    if (withSeparator) {
                        builder.append("&").append(field.getName()).append("=").append(v);
                    } else if (withFieldName) {
                        builder.append(field.getName()).append(v);
                    } else {
                        builder.append(v);
                    }
                });
            } catch (IllegalAccessException e) {
                log.error("拼接字符串异常");
            }
        }
        if (withSeparator) {
            builder.deleteCharAt(0);
        }
        builder.append(Optional.ofNullable(suffix).orElse(""));
        return builder.toString();
    }
}
